//
//  MCConsumeDetailViewController.m
//  ERP
//
//  Created by QA on 15/12/3.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCConsumeDetailViewController.h"

#import "AutoTextTableViewCell.h"
#import "NSDictionary+DataFormat.h"
#import "NSString+handle.h"
#import "MRJobOrderViewController.h"
#import "WebServiceCommonRequest.h"

#import "TYMActivityIndicatorView.h"
#import "NSKeyedArchiverUserLogin.h"
#import "MCConsumeDetailViewCell.h"
#import "GEObjectValueTableViewCell.h"

#import "Charts-Swift.h"
#import "KWFormViewQuickBuilder.h"
#import "GEProgressBarTableViewCell.h"

@interface MCConsumeDetailViewController ()

@property (nonatomic,strong) NSDictionary *contractBaseInfo;
@property (nonatomic,strong) NSMutableArray *contractData;

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@end

@implementation MCConsumeDetailViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"工程消耗明细"];
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    NSArray *valueObject = object;
    if(!(valueObject && [valueObject isKindOfClass:[NSArray class]] && valueObject.count > 0)) return;
    
    self.searchStartTime = valueObject[0];
    self.searchEndTime = valueObject[1];
    NSDictionary *dic = valueObject[2];
    self.contractBaseInfo = dic;
    NSMutableArray *contract = [NSMutableArray array];
    
    [self addContractInfoKey:@"合同编号" toKey:@"合同编号：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"合同名称" toKey:@"合同名称：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工程名称" toKey:@"工程名称：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"施工单位" toKey:@"施工单位：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工地地址" toKey:@"工地地址：" defaults:@"未知" format:nil form:dic toArray:contract];
    //[self addContractInfoKey:@"总消耗量" toKey:@"总消耗量：" defaults:@"未知" format:@"%@吨" form:dic toArray:contract];
    [self addContractInfoKey:@"发货量" toKey:@"发货方量：" defaults:@"未知" format:@"%@方" form:dic toArray:contract];
    [self addContractInfoKey:@"生产量" toKey:@"生产方量：" defaults:@"未知" format:@"%@方" form:dic toArray:contract];
    
    self.contractData = contract;
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[MCConsumeDetailViewCell class] forCellReuseIdentifier:@"MCConsumeDetailViewCell"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.contractData];
        return cell;
        
    } else if(indexPath.section > 0){
        //绘制图表数据
        GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (progressBarCell == nil) {
            NSString *identifierBar = [NSString stringWithFormat:@"MCGEProgressBarTableViewCell%ld",(long)indexPath.section];
            progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
            progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
        }

        //存在数据绘制图表 
        if (progressBarCell.objectValue) {
            NSString *identifier = [NSString stringWithFormat:@"MCChargeInDetailViewController%ld",(long)indexPath.section];
            GEObjectValueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.objectValue = progressBarCell.objectValue;
                
                //添加图表
                if(indexPath.section == 1){ //实验与实际配合比分析
                    [self materialConsumeInCell:cell indexPath:indexPath];
                } else if(indexPath.section == 2){ //施工配合比详情
                    KWFormView *formView = [self reloadTableCell:cell indexPath:indexPath];
                    [cell.contentView addSubview:formView];
                }
            }
            return cell;
        }
        NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
        [parameter setObject:[self.contractBaseInfo objectFormatStringForKey:@"GCID"] forKey:@"GCID"];
        [parameter setObject:self.searchStartTime forKey:@"开始日期"];
        [parameter setObject:self.searchEndTime forKey:@"截止日期"];
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"YCL_DYXH_GCMC_LIST_MX20160129" parameter:parameter index:indexPath.section];
        return progressBarCell;
    }
    
    return nil;
}


- (void)materialConsumeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    NSString *startTime = [self.searchStartTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTime = [self.searchEndTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"工程实际消耗用量统计(吨)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    UIButton *subLable = [[UIButton alloc] initWithFrame:CGRectMake(20, 32, SuperWidth - 40, 22)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    subLable.titleLabel.textAlignment = NSTextAlignmentCenter;
    subLable.userInteractionEnabled = NO;
    [subLable setTitle:[NSString stringWithFormat:@"以下为%@-%@数据",startTime,endTime] forState:UIControlStateNormal];
    [cell.contentView addSubview:subLable];
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 35, SuperWidth, 250.0)];
    _chartView.usePercentValuesEnabled = NO;
    _chartView.holeRadiusPercent = 0;
    _chartView.noDataText = @"暂无数据";
    _chartView.transparentCircleRadiusPercent = 0;
//    _chartView.descriptionText = @"";
    _chartView.drawCenterTextEnabled = NO;
    [_chartView setExtraOffsetsWithLeft:35.f top:20.f right:5.f bottom:5.f];
    
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.0;
    _chartView.rotationEnabled = YES;
    _chartView.highlightPerTapEnabled = YES;
    _chartView.userInteractionEnabled = NO;
    _chartView.drawEntryLabelsEnabled = NO;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    
    l.font = [UIFont systemFontOfSize:11];
    l.textColor = [UIColor darkGrayColor];
    
    [self setData:_chartView data:valueArray];
    [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
    [cell.contentView addSubview:_chartView];
    
}

- (void)setData:(PieChartView *)_chartView data:(NSArray*)valueArray
{
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    
    for (int i=0; i<valueArray.count; i++) {
        NSDictionary *mDictionary = [valueArray objectAtIndex:i];
        NSString *titleName = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        CGFloat yValue = [mDictionary objectFormatFloatForKey:@"实际消耗用量" retain:2 except:1];
        NSString *yValueString = [mDictionary objectFormatFloatStringForKey:@"实际消耗用量" retain:2 except:1000 exceptFormat:@"%@吨" format:@"%@公斤"];
        
        NSString *titleFormt = [NSString stringWithFormat:@"%@  %@",titleName,yValueString];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:yValue label:titleFormt]];
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"原材消耗种类"];
    dataSet.sliceSpace = 2.0;
    dataSet.drawValuesEnabled = NO;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    [colors addObject:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" t";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    _chartView.data = data;
    [_chartView highlightValues:nil];
}


//配合比详情页面设置
- (KWFormView *)reloadTableCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    NSArray *titles = @[@"材料名称",@"设定用量(T)",@"实际用量(T)",@"误差值(T)",@"误差率"];
    //NSArray *titles = @[@"材料名称",@"配比设定用量",@"实际设定用量",@"实际消耗用量",@"误差值",@"误差率"];
    
    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    [builder setBorderColor:[UIColor colorWithWhite:0.88 alpha:1.0]];
    [builder addRecord:titles];
    
    for(int i = 0 ;i < valueArray.count; i++){
        NSDictionary *mDictionary = [valueArray objectAtIndex:i];
        NSString *clggmc = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        NSString *wcl = [mDictionary objectFormatFloatStringForKey:@"误差率" retain:2 format:@"%@%%"];
        CGFloat pbValue = [mDictionary objectFormatFloatForKey:@"配比设定用量" retain:3 except:1000];
        CGFloat xhValue = [mDictionary objectFormatFloatForKey:@"实际消耗用量" retain:3 except:1000];
        CGFloat wczValue = [mDictionary objectFormatFloatForKey:@"误差值" retain:3 except:1000];
        
        NSString *pb = [NSString stringWithFormat:@"%0.3f",pbValue];
        NSString *xh = [NSString stringWithFormat:@"%0.3f",xhValue];
        NSString *wcz = [NSString stringWithFormat:@"%0.3f",wczValue];
        [builder addRecord:@[clggmc,pb,xh,wcz,wcl]];
    }
    
    CGFloat itemWidth = SuperWidth/7;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value4 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value5 = [NSNumber numberWithFloat:(itemWidth*1.5)];
    NSNumber *value6 = [NSNumber numberWithFloat:(itemWidth*1)];
    
    KWFormView *formView = [builder startCreatWithWidths:@[value1,value2,value4,value5,value6] startPoint:CGPointMake(0, 0)];
    formView.mKWFormViewHeight = 30;
    return formView;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"工程基本信息";
    } else if(section == 1){
        lable.text = @"工程消耗占比";
    } else if(section == 2){
        lable.text = @"工程消耗报表";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.contractData];
        return cell.contentView.frame.size.height;
        
    } else if(indexPath.section == 1){
        return 280;
    } else if(indexPath.section == 2){
        GEObjectValueTableViewCell *cell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (!cell.objectValue) return 240;
        KWFormView *formView = [self reloadTableCell:cell indexPath:indexPath];
        return [formView getFormViewHeight] + 3;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

@end
